<template>
	<view id="form">
		<u--form :model="form" :rules="rules" ref="form1">
			<u-form-item labelWidth="70" label="项目名称" required prop="projectName" borderBottom>
				<str-autocomplete :importvalue="form.projectName" :list="projectList" :label="labelFormatter"
					@select="onSelect" @change="onInputChange" highlightColor="#FF0000"></str-autocomplete>
				<u-button class="btn-add" plain icon="plus" type="primary" size="mini" slot="right"
					@click="toAddProject"></u-button>
			</u-form-item>
			<u-form-item labelWidth="70" label="所属区域" required prop="areaName" @click="onGetArea">
				<u--input v-model="form.areaName" disabled disabledColor="#fff" placeholder="选择所属区域" border="none">
				</u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item labelWidth="70" label="定位" required prop="locationAddr" borderBottom @click="onShowMapWrap">
				<u--input v-model="form.locationAddr" disabled disabledColor="#fff" placeholder="选择定位" border="none">
				</u--input>
				<u-icon slot="right" name="map-fill"></u-icon>
			</u-form-item>
			<u-form-item labelWidth="70" label="有无问题" @click="showProblem = true">
				<u--input v-model="form.isProblem1" disabled disabledColor="#fff" placeholder="请选择有无问题" border="none">
				</u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<view>
				<!-- <u-divider text="问题详情" textPosition="center"></u-divider> -->
				<u-form-item labelWidth="70" label="问题等级" @click="showProbLev = true" required prop="problemLevelName">
					<u--input v-model="form.problemLevelName" disabled disabledColor="#fff" placeholder="请选择问题等级"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item labelWidth="70" label="图片">
					<u-upload :capture="['camera']" :fileList="proList" @delete="deletePic('pro')" name="pro" multiple
						:width="40" :height="40" :maxCount="5" @afterRead="fileUpload"></u-upload>
				</u-form-item>
				<u-form-item labelWidth="70" label="视频">
					<u-upload :capture="['camera']" :maxCount="1" accept="video" :fileList="videoList"
						@delete="deletePic('video')" name="video" multiple :width="40" :height="40"
						@afterRead="videoUpload"></u-upload>
				</u-form-item>
				<u-form-item labelWidth="70" label="问题描述" required prop="problemDescribe">
					<u-textarea v-model="form.problemDescribe" placeholder="输入问题描述"></u-textarea>
				</u-form-item>
				<u-form-item labelWidth="100" label="是否需要整改" @click="showRectify = true">
					<u--input v-model="form.isRectify1" disabled disabledColor="#fff" placeholder="请选择是否需要整改"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<view>
					<u-form-item labelWidth="70" label="整改期限" required prop="rectifyTime" @click="showCalendar = true">
						<u--input v-model="form.rectifyTime" disabled disabledColor="#fff" placeholder="请选择整改期限"
							border="none"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item labelWidth="70" label="整改要求" required prop="rectifyDemand">
						<u-textarea v-model="form.rectifyDemand" placeholder="输入整改要求"></u-textarea>
					</u-form-item>
				</view>
<!-- 				<u-form-item labelWidth="70" label="整改回复">
					<u-textarea v-model="form.rectifyResult" placeholder="输入整改回复"></u-textarea>
				</u-form-item>
				<u-form-item labelWidth="70" label="整改图片">
					<u-upload :capture="['camera']" :fileList="resList" @delete="deletePic('res')" name="res" multiple
						:width="40" :height="40" :maxCount="5" useBeforeRead @beforeRead="beforeUpload" @afterRead="fileUpload">
					</u-upload>
				</u-form-item> -->
			</view>
		</u--form>
		<view class="submit-btn">
			<u-button type="primary" :disabled="submitDisabled" :loading="submitLoading" :text="submitText"
				@click="onSubmit"></u-button>
		</view>
		<u-picker closeOnClickOverlay :show="showProblem" :columns="problemOpts" @cancel="onProCancel"
			@confirm="onProConfirm" @close="onClosePro" keyName="title"></u-picker>
		<u-picker closeOnClickOverlay :show="showArea" :loading="cityLoading" ref="cityPicker" :columns="cityColumns"
			@confirm="onCityConfirm" @change="onChangeCity" @cancel="onCityCancel" @close="onCloseCity"
			keyName="areaName"></u-picker>	
		<u-picker closeOnClickOverlay :show="showProbLev" :columns="problemLevOpts" @cancel="onProbCancel"
			@confirm="onLevConfirm" @close="onCloseProb" keyName="title"></u-picker>
		<u-picker closeOnClickOverlay :show="showRectify" :columns="rectifyOpts" @cancel="onRecCancel"
			@confirm="onRecConfirm" @close="onCloseRec" keyName="title"></u-picker>
		<u-datetime-picker :show="showCalendar" v-model="value1" mode="date" @confirm="confirmCalendar"
			@close="calendarClose" @cancel="cancelCalendar"></u-datetime-picker>
		<u-popup :show="showMap" @close="onCloseMap" @open="onShowMap">
			<view class="map_container">
				<map class="map" id="map" :longitude="position.longitude" :latitude="position.latitude"
					:markers="markers" scale="16"></map>
			</view>
			<view class="map_text">
				<view>
					<text class="h1">{{position.name}}</text>
					<text>{{position.desc}}</text>
				</view>
				<view>
					<u-button size="small" type="primary" text="提交" @click="onLocation"></u-button>
				</view>
			</view>
		</u-popup>
		<view style="position: absolute;top: -999999px;">
			<view>
				<canvas style="width: 1000px;height:1000px;" canvas-id="myCanvas"></canvas>
			</view>
		</view>
	</view>
</template>

<script>
	const amapFile = require('@/utils/amap-wx.130')
	const configMap = require('@/utils/config.js')
	import strAutocomplete from '@/components/str-autocomplete/str-autocomplete.vue'
	import config from '@/utils/defaultConfig'
	import {getAreaList,getProjectList} from '@/api/global'
	import {createNo,addPatrol} from '@/api/form'
	import apis from '@/api/apis'
	import {ACCESS_TOKEN} from '@/store/mutaction-types'
		export default { 
			data() {
				return { 
					form: {
						checkNo: '',
						projectName: '',
						projectId: '',
						type: 0,
						typeName: '常规',
						areaId: '',
						areaName: '',
						locationAddr: '',
						isProblem: '1',
						isProblem1: '有问题',
						isRectify: '1',
						isRectify1: '需整改',
						latitude: '',
						longitude: ''
					},
					rules: {
						rectifyTime: [{
							required: true,
							message: '请选择整改期限',
							trigger: ['change']
						}],
						problemDescribe: [{
							required: true,
							message: '必须填写问题描述',
							trigger: ['blur']
						}],
						problemLevelName: [{
							required: true,
							message: '请选择问题等级',
							trigger: ['change']
						}],
						rectifyDemand: [{
							required: true,
							message: '必须填写整改要求',
							trigger: ['blur']
						}]
					},
					showProblem: false,
					problemOpts: [
						config.isProblem
					],
					problemLevOpts: [
						config.problemLevel
					],
					rectifyOpts: [
						config.isRectify
					],
					submitText: '提交',
					submitLoading: false,
					showRectify: false,
					showProbLev: false,
					showCalendar: false,
					showProject: false,
					showArea: false,
					cityLoading: false,
					labelFormatter: 'projectName',
					cityColumns: [],
					projectList: [],
					proList: [],
					resList: [],
					// app_rectify_result_image
				}
			},
			created() {
				this.getBusinessNo()
			},
			methods: {
				getBusinessNo() {
					createNo().then(res => {
						const no = res.data.msg
						const arr = no.split(',')
						this.form.checkNo = arr[0]
						this.form.businessId = arr[1]
					})
					const key = configMap.Config.key
					const myAmapFun = new amapFile.AMapWX({
						key: key
					})
					uni.authorize({
						scope: 'scope.userLocation',
						success: () => {
							uni.getLocation({
								type: 'gcj02',
								success: res => {
									myAmapFun.getRegeo({
										location: `${res.longitude},${res.latitude}`,
										success: add => {
											this.form.locationAddr = add[0].name
											this.form.latitude = res.latitude
											this.form.longitude = res.longitude
										},
										fail: error => {
											console.log(error)
										}
									})
								}
							})
						},
						fail: error => {
							console.log(error)
						}
					})
				},
				deletePic(event) {
					this[`${event}List`].splice(event.index, 1)
				},
				// 有无问题
				onProConfirm(e) {
					this.form.isProblem = e.value[0].id
					this.form.isProblem1 = e.value[0].title
					this.showProblem = false
				},
				onClosePro() {
					this.showProblem = false
				},
				onProCancel() {
					this.showProblem = false
				},
				onRecCancel() {
					this.showRectify = false
				},
				onRecConfirm(e) {
					this.form.isRectify = e.value[0].id
					this.form.isRectify1 = e.value[0].title
					this.showRectify = false
				},
				onCloseRec() {
					this.showRectify = false
				},
				onProbCancel() {
					this.showProbLev = false
				},
				onCloseProb() {
					this.showProbLev = false
				},
				onLevConfirm(e) {
					this.form.problemLevel = e.value[0].id
					this.form.problemLevelName = e.value[0].title
					this.showProbLev = false
				},
				confirmCalendar(e) {
					this.showCalendar = false
					this.form.rectifyTime = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
				},
				onCityConfirm(e) {
					// 街道办事处等没有二级选择，所以报错
					if (e.value[0].children.length == 0) {
						this.form.areaName = e.value[0].areaName
						this.form.areaId = e.value[0].id
					} else {
						this.form.areaName = e.value[1].areaName
						this.form.areaId = e.value[1].id
					}
					this.showArea = false
				},
				calendarClose() {
					this.showCalendar = false
				},
				cancelCalendar() {
					this.showCalendar = false
				},
				onProjCancel() {
					this.showProject = false
				},
				onCloseProj() {
					this.showProject = false
				},
				onCityCancel() {
					this.showArea = false
				},
				onCloseCity(e) {
					this.showArea = false
				},
				toAddProject(e) {
					uni.navigateTo({
						url: '../project/project'
					})
				},
				onGetArea() {
					getAreaList().then(res => {
						this.areaList = res.data.data
						this.cityColumns[0] = this.areaList
						if (this.areaList[0].children.length == 0) {
							this.cityColumns[1] = this.areaList[0]
						} else {
							this.cityColumns[1] = this.areaList[0].children
						}
					}).finally(() => {
						this.showArea = true
					})
				},
				onSelect(opt) {
					this.form.projectId = opt.projectId
					this.form.projectName = opt.projectName
					this.form.areaName = opt.areaFullPath
					this.form.areaId = opt.areaId
				},
				onShowMap() {},
				onShowMapWrap() {
					uni.authorize({
						scope: 'scope.userLocation',
						success: () => {
							uni.chooseLocation({
								success: res => {
									this.form.longitude = res.longitude
									this.form.latitude = res.latitude
									this.form.locationAddr = res.address
								},
								fail: err => {
									console.log(err)
								}
							})
						}
					})
				},
				onInputChange(opt) {
					if (opt !== '') {
						getProjectList(opt).then(res => {
							this.projectList = res.data.data
						}).catch(error => {
							console.log(error)
						})
					}
				},
				onChangeCity(e) {
					const {
						columnIndex,
						index,
						// 微信小程序无法将picker实例传出来，只能通过ref操作
						picker = this.$refs.cityPicker
					} = e
					if (columnIndex === 0) {
						this.cityLoading = true
						uni.$u.sleep(100).then(res => {
							picker.setColumnValues(1, this.areaList[e.index].children)
							this.cityLoading = false
						})
					}
				},
				onSubmit() {
					const app = this
					app.$refs.form1.validate().then(res => {
						app.submitLoading = true
						app.submitText = '上报中'
						addPatrol(app.form).then(res => {
							if (res.data.code === 200) {
								app.submitLoading = false
								app.submitText = '提交'
								uni.$u.toast('提交成功')
								uni.navigateTo({
									url: '/packageD/list/list'
								})
							} else {
								uni.$u.toast(res.msg)
								app.submitLoading = false
								return false
							}
						}).catch(err => {
							uni.$u.toast(err)
							app.submitLoading = false
							return false
						})
					}).catch(errors => {
						app.submitLoading = false
						return false
					})
				},
				async beforeUpload(event) {
					const data = await this.addMask(event.index, event.file, event.name)
					return data
				},
				async fileUpload(event) {
					const app = this
					this.submitText = '上传中'
					this.submitDisabled = true
					let lists = [].concat(event.file)
					let fileListLen = this[`${event.name}List`].length
					lists.map((item) => {
						this[`${event.name}List`].push({
							...item,
							status: 'uploading',
							message: '上传中'
						})
					})
					for (let i = 0; i < lists.length; i++) {
						const url = await this.addMask1(lists[0].url)
						let result = await this.uploadFilePromise(url, this.imageHeader[event.name])
						let item = this[`${event.name}List`][fileListLen]
						this[`${event.name}List`].splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: 'https://bc-p2-file.oss-cn-zhangjiakou.aliyuncs.com/' + result.msg
						}))
						fileListLen++
					}
				},
				uploadFilePromise(url, type) {
					const app = this
					const data = {}
					data['businessId'] = this.form.businessId
					data['businessType'] = type
					return new Promise((resolve, reject) => {
						const a = uni.uploadFile({
							url: 'https://p2.xuzhouzhihui.com/api' + apis.Upload,
							filePath: url,
							name: 'file',
							header: {
								'Authorization': 'Bearer ' + uni.getStorageSync(ACCESS_TOKEN)
							},
							formData: data,
							success: res => {
								setTimeout(() => {
									resolve(JSON.parse(res.data))
									this.submitText = '上报'
									this.submitDisabled = false
								}, 500)
							},
							fail: error => {
								uni.$u.toast(error)
							}
						})
					})
				},
				addMask(index, list, name) {
					return new Promise((resolve, reject) => {
						const app = this
						uni.getImageInfo({
							src: list[index].url,
							success: res => {
								const ctx = uni.createCanvasContext('myCanvas')
								ctx.drawImage(list[index].url, 0, 0, res.width, res.height)
								ctx.font = "12px Georgia"
								ctx.fillStyle = "#eee"
								ctx.fillText("地点:" + app.form.locationAddr, 50, 30) // 设置字体
								ctx.fillText("时间:" + new Date().getTime(), 50, 50) // 设置字体
								ctx.fillText("项目:" + app.form.projectName, 50, 70) // 设置字体
								ctx.fillText("定位:" + app.form.locationAddr, 50, 90) // 设置字体
								ctx.draw(false, () => {
									setTimeout(() => {
										uni.canvasToTempFilePath({
											width: res.width,
											height: res.height,
											canvasId: 'myCanvas',
											success: img => {
												this[`${name}List`][index].thumb = img.tempFilePath
												this[`${name}List`][index].url = img.tempFilePath
												uni.saveImageToPhotosAlbum({
													filePath: img.tempFilePath,
													success: isres => {
														resolve(true)
													}
												})
											}
										})
									}, 1000)
								})
							}
						})
					})
				},
				addMask1(url) {
					return new Promise((resolve, reject) => {
						const app = this
						uni.getImageInfo({
							src: url,
							success: res => {
								const ctx = uni.createCanvasContext('myCanvas')
								ctx.drawImage(url, 0, 0, res.width, res.height)
								ctx.font = "12px Georgia"
								ctx.fillStyle = "#eee"
								ctx.fillText("地点:" + app.form.locationAddr, 50, 30) // 设置字体
								ctx.fillText("时间:" + new Date().getTime(), 50, 50) // 设置字体
								ctx.fillText("项目:" + app.form.projectName, 50, 70) // 设置字体
								ctx.fillText("定位:" + app.form.locationAddr, 50, 90) // 设置字体
								ctx.draw(false, () => {
									setTimeout(() => {
										uni.canvasToTempFilePath({
											width: res.width,
											height: res.height,
											canvasId: 'myCanvas',
											success: img => {
												resolve(img.tempFilePath)
											}
										})
									}, 1000)
								})
							}
						})
					})
				},
			}
		}
</script>

<style scoped>
	#form {
		padding: 0 20upx;
	}
	.btn-add {
		width: 40px;
	}
	
	/* .map_container {
		width: 750upx;
		height: 750upx;
		#map {
			width: 750upx;
			height: 750upx;
		}
	} */
	
	/* .map_text {
		background: #fff;
		padding: 0 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	
		text {
			margin: 5px 0;
			display: block;
			font-size: 12px;
		}
	
		.h1 {
			margin: 15px 0;
			font-size: 15px;
		}
	} */
	
	/* .submit-btn {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		z-index: 9999
	} */
	
</style>